package com.qq.mybatisdemo.configration;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("execution(* com.qq.mybatisdemo..*.*(..))")
    public void pointCut() {
    }

    /**
     * 执行方法前更换数据源
     *
     * @param joinPoint        切点
     * @param targetDataSource 动态数据源
     */
    @Before("@annotation(targetDataSource)")
    public void doBefore(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        String  dataSourceKey = targetDataSource.dataSourceKey();
        if (DataSourceKey.defaultKey.equalsIgnoreCase(dataSourceKey)) {
            DataSourceContextHolder.setDataSourceType(DataSourceKey.defaultKey);
        } else if (DataSourceKey.localKey.equalsIgnoreCase(dataSourceKey)){
            DataSourceContextHolder.setDataSourceType(DataSourceKey.localKey);
        } else if (DataSourceKey.prodKey.equalsIgnoreCase(dataSourceKey)){
            DataSourceContextHolder.setDataSourceType(DataSourceKey.prodKey);
        }else{
            DataSourceContextHolder.setDataSourceType(DataSourceKey.defaultKey);
        }
    }

    /**
     * 执行方法后清除数据源设置
     *
     * @param targetDataSource 动态数据源
     */
    @After("@annotation(targetDataSource)")
    public void doAfter(TargetDataSource targetDataSource) {
        DataSourceContextHolder.clearDataSourceType();
    }


}
